package Controler;

import Module.Blog;
import Module.BlogDao;
import Module.User;
import Module.UserDao;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Creat with IntelliJ IDEA
 * Description
 * User: mamba24
 * Date: 2022-11-24
 * Time: 15:54
 * To BE A Better Person-2020-3-2
 */
@WebServlet("/userInfo")
public class UserInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过这篇文章的blogid来查userid从而找到这个user是谁
        ObjectMapper mapper=new ObjectMapper();
        String blogid=req.getParameter("blogid");
        HttpSession session=req.getSession();
        BlogDao blogDao=new BlogDao();
        UserDao userDao=new UserDao();
        User user= (User) session.getAttribute("user");
        if(session == null){
            resp.setContentType("text/html;charset=utf8");
            resp.setStatus(403);
            resp.getWriter().write("请先登录登录");
            return;
        }
        if(user == null){
            resp.setContentType("text/html;charset=utf8");
            resp.setStatus(403);
            resp.getWriter().write("请先登录登录");
            return;
        }
        if(blogid == null){
            //在博客列表界面
            resp.setContentType("application/json;charset=utf8");
            user.setPassnum(userDao.countPass(user));
            String jsonString= mapper.writeValueAsString(user);
            resp.getWriter().write(jsonString);
        }else {
            //在博客详情界面
            //通过blogid找到userid
            resp.setContentType("application/json;charset=utf8");
            Blog blog=blogDao.search(Integer.parseInt(blogid));
            System.out.println(blog.getUserid());
            User buser=userDao.selectByid(blog.getUserid());
            System.out.println(user.getUserid());
            System.out.println(buser.getUserid());
            if(buser.getUserid() == user.getUserid()){
                buser.setIsYourblog(1);
            }else{
                buser.setIsYourblog(0);
            }
            buser.setPassnum(userDao.countPass(buser));
            System.out.println(buser);
            String jsonString=mapper.writeValueAsString(buser);
            resp.getWriter().write(jsonString);
        }
    }
}
